package cn.weixin.service.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.weixin.common.msg.MsgType;
import cn.weixin.common.msg.req.InputEventMessage;
import cn.weixin.common.msg.req.InputMessage;
import cn.weixin.common.msg.req.InputTextMessage;
import cn.weixin.common.msg.resp.OutputMessage;
import cn.weixin.common.util.XMLUtils;
import cn.weixin.service.handle.HandlerFactory;
import cn.weixin.service.handle.MessageHandler;

/**
 * @author Han
 */
@Service
public class CoreService {
	private static final Logger log = LoggerFactory.getLogger(CoreService.class);
	
	@Autowired
	private HandlerFactory handlerFactory;
	
	
	/**
	 * 处理用户消息
	 * @param inputXml
	 * @return
	 */
	public String excute(String inputXml){
		InputMessage message = (InputMessage) XMLUtils.xml2Vo(inputXml.toString(), InputMessage.class);
		String msgType = message.getMsgType();
		MessageHandler<InputMessage> handler = null;
		switch(msgType){
			case MsgType.REQ_MESSAGE_TYPE_TEXT:
				handler = handlerFactory.getHandler(MsgType.REQ_MESSAGE_TYPE_TEXT);
				message = (InputTextMessage) XMLUtils.xml2Vo(inputXml.toString(), InputTextMessage.class);
				break;
			case MsgType.REQ_MESSAGE_TYPE_EVENT:
				handler = handlerFactory.getHandler(MsgType.REQ_MESSAGE_TYPE_EVENT);
				message = (InputEventMessage) XMLUtils.xml2Vo(inputXml.toString(), InputEventMessage.class);
				break;
			default:
				handler = handlerFactory.getHandler(MsgType.REQ_MESSAGE_DEFAUL);
				break;
		}
		OutputMessage outputMessage = handler.handle(message);
		String outXml = XMLUtils.vo2Xml(outputMessage);
		return outXml;
	}
}
